package jmine.tec.di.wrapper;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import jmine.tec.utils.Tuple;
import jmine.tec.utils.UnmodifiableTuple;

/**
 * Wrapper abstrato para colecoes
 * 
 * @author takeshi
 */
public abstract class AbstractCollectionWrapper extends AbstractWrapper {

    /**
     * {@inheritDoc}
     */
    public boolean checkContainedType(Object resolved, Class<?> requiredComponentClass) {
        Iterator<?> iterator = extractCollectionFrom(resolved).iterator();
        while (iterator.hasNext()) {
            if (!requiredComponentClass.isInstance(iterator.next())) {
                return false;
            }
        }
        return true;
    }

    /**
     * Tenta transformar o objeto passado em uma colecao
     * 
     * @param instance Object
     * @return Collection
     */
    protected Collection<?> extractCollectionFrom(Object instance) {
        return ((Collection<?>) instance);
    }

    /**
     * {@inheritDoc}
     */
    public List<Tuple<?, ?>> collect(Object resolved, String name) {
        List<Tuple<?, ?>> list = new ArrayList<Tuple<?, ?>>();
        Collection<?> collection = extractCollectionFrom(resolved);
        for (Object object : collection) {
            list.add(UnmodifiableTuple.newTuple(name, object));
        }
        return list;
    }

}
